package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {




    @Autowired
   private AddressBookMapper addressBookMapper;
    /**
     * 添加地址簿
     * @param addressBook
     */
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据userId查询所有地址
     * @return
     */
    public List<AddressBook> list() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<AddressBook> addressBookList=  addressBookMapper.selectList(addressBook);
        return addressBookList;
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    public AddressBook selectById(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook= addressBookMapper.selectById(addressBook);
        return addressBook;
    }

    /**
     * 根据id删除地址
     * @param id
     */
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        addressBookMapper.update(addressBook);
    }

    /**
     * 修改为默认地址
     * @param addressBook
     */
    public void updateAddressById(AddressBook addressBook) {
        //先将所有的isDefault置为0
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.setDefault(addressBook);
        //将当前地址设置为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.updateAddressById(addressBook);
    }

    /**
     * 查询默认地址
     * @return
     */
    public AddressBook getDefault() {
        AddressBook addressBook=  addressBookMapper.selectDefault();
        return addressBook;
    }
}
